var productId = getUrlParam('id');
var shareimage = "";
var localUrl = document.location;
//alert(localUrl);
var shareurl1 = "http://weixin.zjpxny.com/details.html?id=" + productId;
var shareName = "";
var shareDesc = "";
var sharePrice = 0;
$(function () {

    var type = getUrlParam('type');
    var id = getUrlParam('id');
    var limitId = getUrlParam('limitId');

    productId = id;
    //获得商品的信息
    getProductDetail(type, id, limitId, memberId);

    //介绍和须知切换
    $('.tab span').click(function () {
        $(this).addClass("on").siblings().removeClass('on');
        if ($(this).index() == 0) {
            $('#xuZhi').hide();
            $('#intro').show();
        } else {
            $('#intro').hide();
            $('#xuZhi').show();
        }
    });

    //点击查看商品详情
    $('#productList').on('tap click', 'li', function () {
        goToProDetails($(this));
    });

    //点击提交按钮
    $('#submitBtn').on('click', function () {
        getMyInfo();
        var paramId = $('#paramPrice').data('id');
        var num = $('#Number').val();
        if ($(this).data('type') == '1') {
            submitFun('buy', type, id, memberId, paramId, num);
        } else {
            submitFun('cat', type, id, memberId, paramId, num);
        }
    });

    $('#colorBox').on('click', 'span', function () {
        if (!$(this).hasClass('click')) {
            $(this).addClass('click').siblings('span').removeClass('click');
            var colorId = $(this).data('id');
            var sizeId = $('#sizeBox').find('.click').data('id') == undefined ? '' : $('#sizeBox').find('.click').data('id');
            //规格参数请求
            getAiParamInfo(id, colorId, sizeId);
        }
    });

    $('#sizeBox').on('click', 'span', function () {
        if (!$(this).hasClass('click')) {
            $(this).addClass('click').siblings('span').removeClass('click');
            var sizeId = $(this).data('id');
            var colorId = $('#colorBox').find('.click').data('id') == undefined ? '' : $('#colorBox').find('.click').data('id');
            //规格参数请求
            getAiParamInfo(id, colorId, sizeId);
        }
    });


    $('#addCarBtn').click(function () {
        openComfirmBox(2);
    });

    $('#ljgmBtn').click(function () {
        getMyInfo();
        if ($(this).data('type') == '-1') {
            alertMsg('还未到时间购买哦！')
        } else {
            openComfirmBox(1);
        }
    })

    function getMyInfo() {
        $.ajax({
            type: "post",
            url: ajaxUrl + "/mobi/member/AdGetInfo",
            async: true,
            data: {'memberId': memberId},
            success: function (data) {
                var info = data.result;
                if (info.mobile == "" || info.mobile == null) {
                    var skipType = "";
                    if (type != 2) { //普通产品
                        skipType = 3;
                    } else {//限时购产品
                        skipType == 4;
                    }
                    window.location.href = 'bind.html?memberId=' + info.id + '&type=' + skipType + '&productId=' + id + '&limitId=' + limitId;
                }
            }
        });
    }
});

function fenxiang() {
    // 'onMenuShareTimeline',       // 分享到朋友圈接口
    //     'onMenuShareAppMessage'
    var ticket = "";
    $.ajax({
        type: "post",
        url: ajaxUrl + "/mobile/weixin/getTicket",
        async: false,
        data: {'memberId': memberId},
        success: function (data) {
            ticket = data.result;
            //  alert(ticket);
        }
    });

    var timestamp = Date.parse(new Date());
    var nonceStr = "77889900"

    var a = 'jsapi_ticket=' + ticket +
        '&noncestr=' + nonceStr + '&timestamp=' + timestamp + '&url=' + localUrl;
    wx.config({
        // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        debug: false,
        // 必填，公众号的唯一标识
        appId: 'wx5a7259af417cf2e9',
        // 必填，生成签名的时间戳
        timestamp: "" + timestamp,
        // 必填，生成签名的随机串
        nonceStr: nonceStr,
        // 必填，签名
        signature: SHA1(a),
        // 必填，需要使用的JS接口列表
        jsApiList: ['onMenuShareTimeline',       // 分享到朋友圈接口
            'onMenuShareAppMessage']
    });


    wx.error(function (res) {
        alert("出错了：" + res.errMsg);//这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
    });

    wx.ready(function () {
        wx.checkJsApi({
            jsApiList: ['onMenuShareTimeline',       // 分享到朋友圈接口
                'onMenuShareAppMessage'],
            success: function (res) {
                sharetoFriend();
                ifun();
            },
            fail: function (res) {
                alert("fail: " + res);
            },
            complete: function (res) {
                //    alert("complete: "+res);
            },
            cancel: function (res) {
                alert("cancel: " + res);
            }
        });

        //  alert("121212");
        // var url = document.location;
        // // alert("aa")
        // alert(url);
        // wx.onMenuShareAppMessage({
        //     title: '品行惠商品', // 分享标题
        //     desc: '666', // 分享描述
        //     link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        //     imgUrl: '', // 分享图标
        //     type: '', // 分享类型,music、video或link，不填默认为link
        //     dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        //     success: function () {
        //         alert("分享成功");
        //     }
        // });
        //     ifun();
        //  sharetoFriend();
        //点击按钮扫描二维码
        // document.querySelector('#scanQRCode').onclick = function () {};
        // ifun();
        // function ifun() {
        //
        //     wx.scanQRCode({
        //         needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        //         scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
        //         success: function (res) {
        //             var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
        //             alert("扫描结果：" + result);
        //             window.location.href = result;//因为我这边是扫描后有个链接，然后跳转到该页面
        //         },
        //         cancel:function (aa) {
        //             history.back();
        //         }
        //     });
        //
        // }
    });
}


function sharetoFriend() {
    // alert("121212");
    //  var url = document.location;
    // alert("aa")
    //   alert(localUrl);//
    wx.onMenuShareAppMessage({
        title: "品行惠|" + sharePrice + "元 " + shareName, // 分享标题
        desc: shareDesc, // 分享描述
        link: shareurl1, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: shareimage, // 分享图标
        type: '', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        success: function () {
            //   alert(url);
            //    alert("分享成功");
        }
    });
}

function ifun() {
    var url = document.location;
    wx.onMenuShareTimeline({
        title: "品行惠|" + sharePrice + "元 " + shareName, // 分享标题
        link: shareurl1, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: shareimage, // 分享图标
        success: function () {
            // alert("fenxiang");
        },
    });

}

function submitFun(mark, type, id, memberId, paramId, num) {
    if (mark == 'buy') {
        //直接跳转链接
        window.location.href = 'confirmOrder.html?type=' + type + '&id=' + id + '&paramId=' + paramId + '&num=' + num;
    } else {

        $.ajax({
            type: "post",
            url: ajaxUrl + '/mobi/cart/AaAddCart',
            async: true,
            data: {'type': type, 'productId': id, 'paramId': paramId, 'memberId': memberId, 'num': num},
            success: function (data) {
                if (data.code == 0) {
                    alertMsg('成功加入购物车');
                } else {
                    alertMsg('加入购物车失败');
                }
            },
            error: function () {
                errorTip();
            },
            complete: function () {
                $('#ComfirmBox').hide();
            }
        });

    }
}

//产品规格
function getNormal(id, memberId, valueId) {
    $.ajax({
        type: "post",
        url: ajaxUrl + "/mobile/product/getNormal",
        async: true,
        data: {'productId': id, 'memberId': memberId, 'valueIds': valueId},
        success: function (data) {


            $('#select-price').html('<i>￥</i>' + data.result.salePriceView);
            $('#select-stock').text("库存:" + data.result.store);
            $('#select-name').text("已选择:" + data.result.salePriceView);
            console.log("规格id:" + data.result.id);
            $(this).attr("vid", data.id);
        }
    });
}

//添加到购物车
//产品详情设置
function getProductDetail(type, id, limitId, memberId) {
    $.ajax({
        type: "post",
        url: ajaxUrl + "/mobile/product/productDetail",
        async: false,
        data: {'type': type, 'productId': id, 'limitId': limitId, 'memberId': memberId},
        success: function (res) {
            if (res.code == 0) {
                var result = res.result;
                var imgArr = result.images;
                var imgSlideS = '';
                var imgNavS = '';
                shareName = result.productName;
                shareDesc = result.summary;
                shareimage = result.image;
                sharePrice = result.salePrice.toFixed(2);
                for (var i = 0; i < imgArr.length; i++) {
                    if (i == 0) {
                        imgNavS += '<li class="swiper-slide"> <a href="javascript:;"><img src="' + imgArr[i].image + '" alt=""></a></li>'
                        //    shareimage=imgArr[i].image;
                    } else {
                        imgNavS += '<li class="swiper-slide"> <a href="javascript:;"><img src="' + imgArr[i].image + '" alt=""></a></li>'
                    }
                }
                //console.log(imgNavS)
                $('#lunbo').html(imgNavS);


                $('#now').text('￥ ' + result.salePrice.toFixed(2)+"   会员价:￥"+result.vipPrice.toFixed(2));
                $('#stock').text("库存" + result.store);
                $('#name').text(result.productName);
                $('#des').text(result.summary);
                $('#sell').text("已售" + result.saleCount);
                var coms = result.comments;
                $('#pjTitle').html("用户评价<i>(" + coms.length + ")</i>");
                if (coms.length > 0) {
                    var coms1 = coms[0];
                    $('#pjLogo').attr('src', coms1.memberLogo);
                    $('#pjname').text(coms1.memberName);
                    $('#pjtext').text(coms1.content);
                } else {

                    $('#pjliebiao').html("");
                }
                //alert($('#ggvalue').attr("value"));
                //商品详情
                $('#details').html(result.detail);


                //规格
                $('#tcLogo').attr('src', result.image);
                var normals = result.normals[0].normses;
                var normalStr = '';
                for (var i = 0; i < normals.length; i++) {
                    //  console.log(normals[i].valueId);
                    if (i == 0) {
                        normalStr += '<div  class="spec-item " value="' + normals[i].valueId + '">' + normals[i].value + '</div>'
                    } else {
                        normalStr += '<div  class="spec-item" value="' + normals[i].valueId + '">' + normals[i].value + '</div>'
                    }
                }
                $('#spec-list').html(normalStr);

                $('.spec .spec-item').click(function () {
                    $(this).addClass('on').siblings().removeClass('on');
                    var valueId = $(this).attr("value");
                    //.attr("width","180");

                    getNormal(id, memberId, valueId);
                })

                if (result.isCollect == 1) {
                    //   alert("shoucang")
                    $('.top-right').addClass("on");
                }

                //推荐产品
                var products = result.products;
                var tuijianHtml = "";
                for (var i = 0; i < 6 && i < products.length; i++) {
                    tuijianHtml += ' <div href="http://baidu.com" class="list-item">' +
                        '<a href="details.html?id='+products[i].productId+'"    >'+
                        '        <img onclick="proDetail(' + [i].productId + ')" src="' + products[i].image + '" class="img" alt="">' +
                        '        <div class="name">' + products[i].productName + '</div>' +
                        '</a>'+
                        '        <div class="bottom">' +
                        '            <div class="price">￥' + products[i].price + '</div>' +
                        '            <div onclick="addCart(' + products[i].productId + ')" class="add-cart"></div>' +
                        '        </div>' +
                        '    </div>';
                }
                $("#tuijianList").html(tuijianHtml);

                //轮播
                var swiper = new Swiper('.banner', {
                    spaceBetween: 0,  //每个slider之间间距
                    nextButton: '.swiper-button-next',
                    prevButton: '.swiper-button-prev',
                    pagination: '.swiper-pagination',  //生成小圆点
                    paginationClickable: true, //允许点击
                    loop: true,
                    autoplay: 4000,
                    autoplayDisableOnInteraction: false
                });

                fenxiang();

            } else {
                programErrorTip();
            }
        },
        error: function () {
            errorTip();
        }
    });
}


function addCart(productId) {
    $.ajax({
        type: "post",
        url: ajaxUrl + '/mobile/carItem/addProduct',
        async: true,
        //productId=412&memberId=623&normalId=508&num=1
        data: {'memberId': memberId, 'productId': productId, 'normalId': null, 'num': 1},
        success: function (data) {
            if (data.code == 0) {
                alertMsg('成功加入购物车');
            } else {
                alertMsg(data.message);
            }
            $('.spec-section').removeClass('on');
            $('.mask').hide();
            cartNum();
        },
        error: function () {
            errorTip();
        },
        complete: function () {

        }
    });
}
function openComfirmBox(type) {
    $('#ComfirmBox').show();
    if (type == 1) {
        $('#submitBtn').val('立即购买').data('type', '1');
    } else if (type == 2) {
        $('#submitBtn').val('加入购物车').data('type', '2');
    }
}

function ChangeNumber(val) {
    var count = document.getElementById("Number");
    if (val == 1) {
        count.value++;
    }
    else {
        if (count.value > 1) {
            count.value--;
        }
    }
}

function getAiParamInfo(id, colorId, sizeId) {
    $.ajax({
        type: "post",
        url: ajaxUrl + "/mobi/product/AiParamInfo",
        async: true,
        data: {'id': id, 'colorId': colorId, 'sizeId': sizeId},
        success: function (data) {
            $('#paramPrice').text(data.result.price).data('id', data.result.id);
            $('#paramStore').text(data.result.value);
        }
    });
}


function proDetail(id) {
    window.location.href = 'details.html?id=' + id;
}

function getAfH5Info(id) {
    $.ajax({
        type: "post",
        url: ajaxUrl + "/mobi/weixin/AbProductText",
        async: true,
        data: {'productId': id},
        success: function (data) {
            $('#intro').find('.block').html(data.result.productText);
            $('#xuZhi').find('.block').html(data.result.buyInfo);
        }
    });
}


function reloadSlider() {
    var active = 0, as = document.getElementById('pagenavi').getElementsByTagName('a');
    for (var i = 0; i < as.length; i++) {
        (function () {
            var j = i;
            as[i].onclick = function () {
                t.slide(j);
                return false;
            };
        })();
    }
    var t = new TouchSlider({
        id: 'slider',
        speed: 600,
        timeout: 2000,
        before: function (index) {
            as[active].className = '';
            active = index;
            as[active].className = 'active';
        }
    });
}


function shoucang() {


    $.ajax({

        type: "post",
        url: ajaxUrl + "/mobile/collect/doCollect",
        async: true,
        data: {'memberId': memberId, "objId": productId},
        success: function (data) {

            // if ($('.top-right').hasClass('on')) {
            //     $('.top-right').removeClass('on');
            //    // $('.mask').hide();
            // } else {
            //     $('.top-right').addClass('on');
            //    // $('.mask).show();
            // }


            // init();
        }
    });

    if ($('.top-right').hasClass('on')) {
        $('.top-right').removeClass('on');
        // $('.mask').hide();
    } else {
        $('.top-right').addClass('on');
        // $('.mask').show();
    }

}

function timer(intDiff) {
    window.setInterval(function () {
        var day = 0,
            hour = 00,
            minute = 0,
            second = 0;//时间默认值
        if (intDiff > 0) {
            day = Math.floor(intDiff / (60 * 60 * 24));
            hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
            minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
            second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
        }
        if (minute <= 9) minute = '0' + minute;
        if (second <= 9) second = '0' + second;
        $('#hour_show').html('<s id="h"></s>' + hour + '');
        $('#minute_show').html('<s></s>' + minute + '');
        $('#second_show').html('<s></s>' + second + '');
        intDiff--;
    }, 1000);
}